package com.m1905hd.web.controller

import com.m1905hd.common.global.JSONCode
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.apache.shiro.session.Session
import org.apache.shiro.session.mgt.eis.SessionDAO
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod

/**
 *
 * @author weiwei.huang
 * @email ihuangweiwei@163.com
 * @date 15/4/2
 */
@Controller
@RequestMapping("session")
class SessionController {

    @Autowired
    SessionDAO sessionDAO

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("session:view")
    def showList() {
        return "session/list"
    }

    @RequestMapping("list.json")
    @RequiresPermissions("session:view")
    def list() {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        def data = new ArrayList()
        sessions.each {
            try {
                data.add([id: it.id, userName: it.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY").cachedToString, host: it.host, start: it.startTimestamp, last: it.lastAccessTime])
            } catch (e) {

            }
        }
        [results: sessions.size(), rows: data]
    }

    @RequestMapping("forceLogout/{sessionId}.json")
    @RequiresPermissions("session:edit")
    def forceLogout(
            @PathVariable("sessionId") String sessionId) {
        try {
            Session session = sessionDAO.readSession(sessionId);
            if (session != null) {
                session.setTimeout(0)
            }
            return [code: JSONCode.SUCCESS.code]
        } catch (Exception e) {/*ignore*/
            e.printStackTrace()
        }
        [code: JSONCode.ERROR.code]
    }
}
